import 'dart:convert';
import 'dart:io';

/**
 * Create by marven
 * data  2019/1/11
 * des: 网络请求封装
 */
import 'package:dio/dio.dart';
import 'package:jicaimao_flutter/utils/api_address.dart';

class HttpUtil {
  var mConnectionTimeOut = 30 * 1000;
  var mReceiveTimeOut = 3000;
  static HttpUtil instance;
  Dio dio;
  Options options;

  ///实例化

  static HttpUtil getInstance() {
    print('getInstance');
    if (instance == null) {
      instance = new HttpUtil();
    }

    return instance;
  }

  HttpUtil({ResponseType type = ResponseType.JSON}) {
    print('dio复值');
    //通过options 来创建dio实例
    options = Options(
        baseUrl: NetAddress.baseHost,
        connectTimeout: mConnectionTimeOut,
        responseType: type,
        ///  响应流上前后两次接受到数据的间隔，单位为毫秒。如果两次间隔超过[receiveTimeout]，
        ///  [Dio] 将会抛出一个[DioErrorType.RECEIVE_TIMEOUT]的异常.
        ///  注意: 这并不是接收数据的总时限.
        receiveTimeout: mReceiveTimeOut,
        contentType: ContentType.parse("application/x-www-form-urlencoded"),
        headers: {
//         'Content-Type': 'application/x-www-form-urlencoded'
        });
    dio = new Dio(options);
  }

  /// get 请求

  get(url, {data, options, cancelToken}) async {
    print('get请求启动! url：$url ,body: $data');
    Response response;
    try {
      response = await dio.get(
        url,
        data: data,
        cancelToken: cancelToken,
      );
      print('get请求成功!response.data：${response.data}');
    } on DioError catch (e) {
      if (CancelToken.isCancel(e)) {
        print('get请求取消! ' + e.message);
      }
      print('get请求发生错误：$e');
    }
    return response.data;
  }

  /// post 请求

  post(url, {data, options, cancelToken}) async {
    print('post请求启动! url：$url ,body: $data');
    Response response;
    try {
      response = await dio.post(
        url,
        data: data,
        cancelToken: cancelToken,
      );
      print(response);
      return response.data;
    } on DioError catch (e) {
      if (CancelToken.isCancel(e)) {
        print('post请求取消! ' + e.message);
      }
      print('post请求发生错误：$e');
    }
    print('post请求完成：$response');
    return response.data;
  }
}
